import { defineStore } from 'pinia'
import { ref, reactive, nextTick } from 'vue'
import { 
  getConversations, 
  sendMessage as sendMessageApi, 
  sendMessageStream,
  createConversation as createConversationApi,
  deleteConversation as deleteConversationApi,
  updateConversationTitle
} from '@/api/chat'

export const useChatStore = defineStore('chat', () => {
  const conversations = ref([])
  const currentConversationId = ref(null)
  const loading = ref(false)

  const loadConversations = async () => {
    loading.value = true
    try {
      const data = await getConversations()
      console.log('加载的对话数据:', data)
      conversations.value = data || []
      
      if (conversations.value.length > 0 && !currentConversationId.value) {
        currentConversationId.value = conversations.value[0].id
      } else if (conversations.value.length === 0) {
        // 如果没有对话，创建一个默认对话
        console.log('没有对话，创建默认对话')
        await createConversation()
      }
    } catch (error) {
      console.error('加载对话失败:', error)
      // 如果加载失败且没有对话，创建一个默认对话
      if (conversations.value.length === 0) {
        try {
          await createConversation()
        } catch (createError) {
          console.error('创建默认对话失败:', createError)
        }
      }
    } finally {
      loading.value = false
    }
  }

  const createConversation = async (title = '新对话') => {
    try {
      const newConv = await createConversationApi(title)
      conversations.value.unshift(newConv) // 添加到开头
      currentConversationId.value = newConv.id
      return newConv
    } catch (error) {
      console.error('创建对话失败:', error)
      throw error
    }
  }

  const deleteConversation = async (id) => {
    try {
      await deleteConversationApi(id)
      const index = conversations.value.findIndex(c => c.id === id)
      if (index > -1) {
        conversations.value.splice(index, 1)
        if (currentConversationId.value === id && conversations.value.length > 0) {
          currentConversationId.value = conversations.value[0].id
        } else if (conversations.value.length === 0) {
          // 如果没有对话了，创建一个新的
          await createConversation()
        }
      }
    } catch (error) {
      console.error('删除对话失败:', error)
      throw error
    }
  }

  const sendMessage = async (content, useStream = true) => {
    let conversation = conversations.value.find(c => c.id === currentConversationId.value)
    
    // 如果没有当前对话，创建一个新的
    if (!conversation) {
      conversation = await createConversation()
    }

    // 如果这是第一条用户消息，更新对话标题
    const isFirstMessage = conversation.messages.length === 0
    if (isFirstMessage) {
      // 截取前20个字符作为标题
      const newTitle = content.length > 20 ? content.substring(0, 20) + '...' : content
      conversation.title = newTitle
      
      // 调用API更新标题
      try {
        await updateConversationTitle(conversation.id, newTitle)
      } catch (error) {
        console.error('更新对话标题失败:', error)
      }
    }

    const userMessage = {
      id: Date.now(),
      content,
      sender: 'user',
      timestamp: new Date().toISOString()
    }
    
    conversation.messages.push(userMessage)

    // 创建机器人消息占位符（使用 reactive 确保响应式更新）
    const botMessage = reactive({
      id: Date.now() + 1,
      content: '',
      reasoning: '', // 添加 reasoning 字段
      sender: 'bot',
      timestamp: new Date().toISOString(),
      streaming: true
    })
    conversation.messages.push(botMessage)
    
    // 获取消息在数组中的索引，用于后续更新
    const messageIndex = conversation.messages.length - 1

    if (useStream) {
      // 打字机效果变量
      let typewriterTimer = null
      let streamComplete = false
      let firstDataReceived = false
      
      // 启动打字机效果 - 实时逐字显示接收到的内容
      const startTypewriter = () => {
        const speed = 25 // 打字速度（毫秒/字符）
        let contentQueue = []
        let reasoningQueue = []
        let isTyping = false
        
        const typeNextChar = () => {
          if (isTyping) return
          isTyping = true
          
          // 优先处理 reasoning 队列
          if (reasoningQueue.length > 0) {
            const char = reasoningQueue.shift()
            const newReasoning = botMessage.reasoning + char
            botMessage.reasoning = newReasoning
            // 同时更新数组中的消息对象，确保响应式更新
            conversation.messages[messageIndex].reasoning = newReasoning
          }
          // 然后处理 content 队列
          else if (contentQueue.length > 0) {
            const char = contentQueue.shift()
            const newContent = botMessage.content + char
            botMessage.content = newContent
            // 同时更新数组中的消息对象，确保响应式更新
            conversation.messages[messageIndex].content = newContent
          }
          
          isTyping = false
          
          // 如果还有字符要显示，继续
          if (contentQueue.length > 0 || reasoningQueue.length > 0) {
            setTimeout(typeNextChar, speed)
          }
          // 如果流已完成且队列为空，停止流式状态
          else if (streamComplete) {
            botMessage.streaming = false
            conversation.messages[messageIndex].streaming = false
            if (typewriterTimer) {
              clearInterval(typewriterTimer)
              typewriterTimer = null
            }
          }
        }
        
        // 定期检查是否有新字符需要显示（备用机制）
        typewriterTimer = setInterval(() => {
          if (!isTyping && (contentQueue.length > 0 || reasoningQueue.length > 0)) {
            typeNextChar()
          }
          // 如果流已完成且队列为空，清理定时器
          else if (streamComplete && contentQueue.length === 0 && reasoningQueue.length === 0) {
            botMessage.streaming = false
            conversation.messages[messageIndex].streaming = false
            clearInterval(typewriterTimer)
            typewriterTimer = null
          }
        }, speed)
        
        return {
          addContent: (text) => {
            // 将新内容逐字符添加到队列
            for (const char of text) {
              contentQueue.push(char)
            }
            // 如果当前没在打字，立即开始
            if (!isTyping) {
              setTimeout(typeNextChar, 0) // 异步执行，避免阻塞
            }
          },
          addReasoning: (text) => {
            // 将新推理内容逐字符添加到队列
            for (const char of text) {
              reasoningQueue.push(char)
            }
            // 如果当前没在打字，立即开始
            if (!isTyping) {
              setTimeout(typeNextChar, 0) // 异步执行，避免阻塞
            }
          }
        }
      }
      
      // 使用流式接口
      try {
        const typewriter = startTypewriter()
        
        await sendMessageStream(
          currentConversationId.value,
          content,
          // onMessage: 接收到新内容时的回调（实时显示）
          (data) => {
            // 收到第一个数据块时，确保气泡已显示
            if (!firstDataReceived) {
              firstDataReceived = true
            }
            
            if (data.type === 'content') {
              typewriter.addContent(data.content)
            } else if (data.type === 'reasoning') {
              typewriter.addReasoning(data.content)
            }
          },
          // onError: 发生错误时的回调
          (error) => {
            console.error('流式发送消息失败:', error)
            // 清理定时器
            if (typewriterTimer) {
              clearInterval(typewriterTimer)
              typewriterTimer = null
            }
            // 显示错误信息
            const errorContent = botMessage.content || `发送消息失败: ${error}`
            botMessage.content = errorContent
            botMessage.streaming = false
            conversation.messages[messageIndex].content = errorContent
            conversation.messages[messageIndex].streaming = false
          },
          // onComplete: 完成时的回调
          () => {
            streamComplete = true
            // 打字机效果会自动检测并停止
          }
        )
      } catch (error) {
        console.error('流式发送消息失败:', error)
        // 清理定时器
        if (typewriterTimer) {
          clearInterval(typewriterTimer)
          typewriterTimer = null
        }
        const errorContent = `发送消息失败: ${error.message}`
        botMessage.content = errorContent
        botMessage.streaming = false
        conversation.messages[messageIndex].content = errorContent
        conversation.messages[messageIndex].streaming = false
        throw error // 重新抛出错误以便上层处理
      }
    } else {
      // 使用非流式接口（兼容模式）
      try {
        const response = await sendMessageApi(currentConversationId.value, content)
        botMessage.content = response.reply
        botMessage.streaming = false
        conversation.messages[messageIndex].content = response.reply
        conversation.messages[messageIndex].streaming = false
      } catch (error) {
        console.error('发送消息失败:', error)
        const errorContent = `发送消息失败: ${error.message}`
        botMessage.content = errorContent
        botMessage.streaming = false
        conversation.messages[messageIndex].content = errorContent
        conversation.messages[messageIndex].streaming = false
        throw error // 重新抛出错误以便上层处理
      }
    }
  }

  const getCurrentConversation = () => {
    return conversations.value.find(c => c.id === currentConversationId.value)
  }

  return {
    conversations,
    currentConversationId,
    loading,
    loadConversations,
    createConversation,
    deleteConversation,
    sendMessage,
    getCurrentConversation
  }
})
